import { App } from './app';
import Util from './util';
import { Page } from './page';
import './dx-ext';


App.registerRoute({
	name:"data/dealer",
	onLoad:function(context,$container){
		let page=new Page($container);

		let origin=context.params.id;
		let origin_name = context.params.name;
		let columns="";
		if(origin){
			page.crudLayout({title:"经销商管理"});
			page.content.html(`<div class="panel panel-default">
		    <div class="panel-heading font-bold">
			      进口商${origin_name}
			    </div>
			    <div class="panel-body">
			    	<div class="toolbar1"></div>
			    	<div class="data-grid"></div>
			    </div>
		  	</div>`);	
			let filter = [['importer_id','=',origin]]

			let store = $.crudStore(API('restful?_model=sys-importer-dealer'), {
					onLoading: function(loadOptions) {
						loadOptions.filter = filter;
					}
				});
			columns = {
				dataSource:store,
				columns:[{
					caption:'id',
					dataField:'id'
				},{
					caption:'经销商名称',
					dataField:'dealer.name'
				},{
					caption:'备注',
					dataField:'remark'
				},{
					caption:'地址',
					dataField:'dealer.area_name'
				},{
					caption:'操作',
					dataField:'dealer.id',
					cellTemplate:function(container,options){
						$("<a>").text('编辑').css({"text-decoration":"underline"}).click(function(){
							App.getEventContext().redirect(`#/data/new_dealer?openid=${options.data.dealer.id}&id=${origin}&name=${origin_name}`)
						}).appendTo(container)
					}
				}]
			}

			page.content.find('.toolbar1').dxToolbar({
			items:[{
				widget:'dxButton',
			location:"before",
			options:{
				text:"增加经销商",
				onClick:function(e){
						App.getEventContext().redirect(`#/data/new_dealer?id=${origin}&name=${origin_name}&dataset=${origin}`); 
					}
				}
			}]
		});

		}else{ 

		page.crudLayout({title:'进口商管理'});
		page.content.html(`<div class="panel panel-default">
		    <div class="panel-heading font-bold">
			      进口商管理
			    </div>
			    <div class="panel-body">
			    	<div class="toolbar1"></div>
			    	<div class="data-grid"></div>
			    </div>
		  	</div>`);

		columns = {
			dataSource:$.crudStore(API("restful?_model=sys-importer")),
			columns:[{
				caption:'id',
				dataField:'id'
			},{
				caption:'进口商名称',
				dataField:'name'
			},{
				caption:'备注',
				dataField:'remark'
			},{
				caption:'经销商',
				dataField:'dealers_name'
			},{
				caption:'操作',
				dataField:"id",
				cellTemplate:function(container,options){
					let $html = $('<div><a>编辑</a> |<a>添加经销商</a></div>')
					$html.find("a").css({"text-decoration":'underline'})

					$html.find('a:first').click(function(){
						App.getEventContext().redirect(`#/data/new_dealer?importer=${options.value}`);
					})

					$html.find('a:last').click(function(){
						App.getEventContext().redirect(`#/data/dealer?id=${options.value}&name=${options.data.name}`);
					})

					$html.appendTo(container)
					
				}
			}]
		}

			page.content.find('.toolbar1').dxToolbar({
			items:[{
				widget:'dxButton',
			location:"before",
			options:{
				text:"增加",
				onClick:function(e){
						App.getEventContext().redirect('#/data/new_dealer'); 
					}
				}
			}]
		});

			}

		
		

	 page.content.find('.data-grid').dxDataGrid(columns)

	}
})



App.registerRoute({
	name:'data/new_dealer',
	onLoad:function(context,$container){
		let page=new Page($container);
		let origin=context.params.dataset;
		let origin_id=context.params.openid;
		let origin_name = context.params.name;
		let ID = context.params.id;
		let importer = context.params.importer;

		console.log(importer);

		if(origin || origin_id || ID){
			page.crudLayout({title:'经销商'});

			page.content.html(`<div class="panel panel-default">
			    <div class="panel-heading font-bold">
			      经销商管理
			    </div>
			    <div class="panel-body">
			    	<div class="data-grid"></div>
			    </div>
		  	</div>`);

			page.content.find(".data-grid").css({"padding":"20px"});

			let store = '';

			

			let items = [{
				colCount:2,
				itemType:'group',
				items:[{
					label:{text:'经销商名称'},
					dataField:'name'
				},{
					label:{text:' '},
					editorType:'dxSelectBox',
					editorOptions:{
						dataSource:$.crudStore(API("restful?_model=sys-dealer")),
						displayExpr:'name',
						valueExpr:'id',
						showClearButton:true,
						searchEnabled:true,
						onValueChanged:function(e){
						 
							let instance = page.content.find(".data-grid").dxForm('instance')
							$.get(API(`restful/${e.value}?_model=sys-dealer`)).then(res =>{
								instance.option('formData',res.data);
								let area_code=res.data.area_code;
								if(area_code){ 
								let country = area_code.slice(0,2)+'0000',city=area_code.slice(0,4)+'00' 
								$.get(API("areas")).then(resp =>{
										let data =  resp;
								
									page.content.find(".select_country").dxSelectBox("instance").option("dataSource",resp);
									page.content.find(".select_country").dxSelectBox("instance").option("value",country);
									data.forEach( item =>{
										if(item.value == country){

											page.content.find(".select_city").dxSelectBox("instance").option("dataSource",item.child);
											page.content.find(".select_city").dxSelectBox("instance").option("value",city);
											return item.child.forEach(it=>{
												if(it .value == city)
												page.content.find(".select_region").dxSelectBox("instance").option("dataSource",it.child);
												page.content.find(".select_region").dxSelectBox("instance").option("value",area_code);
													
													})
												}
											})
									
								})
								};
							})
							
						}
					}

				}]
			},{
				label:{text:'地址'},
				itemType:'group',
				colCount:3,
				items:[{
					label:{text:'省级'},
					template:function(data){
					return $("<div class='select_country'>").dxSelectBox({
								placeholder:'请选择省级',
								dataSource:$.crudStore(API("areas")),
								displayExpr:"name",
								valueExpr:'value',
								searchEnabled:true,
								onSelectionChanged:function(e){
									
									if(!e.selectedItem){return }
							page.content.find(".select_city").dxSelectBox("instance").option('dataSource',e.selectedItem.child);
							page.content.find(".select_region").dxSelectBox("instance").option("dataSource",[])
								}
							})
					}
				},{
					label:{text:'市级'},
					template:function(data){
					return	$("<div class='select_city'>").dxSelectBox({placeholder:'请选择市级',displayExpr:"name",
								valueExpr:'value',
								searchEnabled:true,
								noDataText:'请先选择前一级',
								onSelectionChanged:function(e){
									if(!e.selectedItem){return }
									page.content.find(".select_region").dxSelectBox("instance").option("dataSource",e.selectedItem.child)
								}
							})
					}
				},{
					label:{text:'地区'},
					template:function(data){
					return	$("<div class='select_region'>").dxSelectBox({placeholder:'请选择区域',displayExpr:"name",
								valueExpr:'value',
								searchEnabled:true,
								noDataText:'请先选择前一级',
								onSelectionChanged:function(e){
								
									if(!e.selectedItem){return }
									page.content.find(".data-grid").dxForm("instance").option('formData.area_code',e.selectedItem.value);
								}
							})
					}
				}]
			},{
				label:{text:'具体门牌号'},
				dataField:'detail'
			},{
				label:{text:'联系电话'},
				dataField:'tel'
			},
			{
				editorType:'dxButton',
				editorOptions:{
					text:function(){if(origin_id){return '修改'}else{return '创建'}},
					type:'success',
					useSubmitBehavior:false,
					onClick:function(e){
						let data=page.content.find(".data-grid").dxForm("instance").option('formData');
						data.importer_id=origin;
						if(origin_id){
							$.crudStore(API(`restful?_model=sys-dealer`)).update(origin_id,data).then((index,res)=>{
							
							DevExpress.ui.notify({message:"修改成功"},"success",1500) ;

							setTimeout(function(){window.history.go(-1)},1500)

						}).fail(res=>{
							DevExpress.ui.notify({message:"请检查"},"warning",2000) 
						})

						return
						}
						$.ajax({url:API('restful?_model=sys-dealer'),method:'post',data:data}).always((res)=>{
							if(res.status == 'success'){ 
							DevExpress.ui.notify({message:"创建成功"},"success",1500) ;

							setTimeout(function(){window.history.go(-1);},1500)

						}else{  
								DevExpress.ui.notify({message:function(){
									let text = '错误：'+res.responseJSON.message;
									return text
								}},"warning",1500) 
							}
						})
					}
				}
			}
			];

			if(origin_id){
				store = $.crudStore(API(`restful/${origin_id}?_model=sys-dealer`));
				$.get(API(`restful/${origin_id}?_model=sys-dealer`)).then(res =>{
					page.content.find(".data-grid").dxForm({
					formData:res.data,
					showColonAfterLabel: true,
					colCount:1,
					items:items
					})
				

				let area_code=res.data.area_code;

				let country = area_code.slice(0,2)+'0000',city=area_code.slice(0,4)+'00' ;
								$.get(API("areas")).then(resp =>{
									let data =  resp;
									page.content.find(".select_country").dxSelectBox("instance").option("dataSource",resp);
									page.content.find(".select_country").dxSelectBox("instance").option("value",country);
									data.forEach( item =>{
										if(item.value == country){

											page.content.find(".select_city").dxSelectBox("instance").option("dataSource",item.child);
											page.content.find(".select_city").dxSelectBox("instance").option("value",city);
											return item.child.forEach(it=>{
												if(it .value == city)
												page.content.find(".select_region").dxSelectBox("instance").option("dataSource",it.child);
												page.content.find(".select_region").dxSelectBox("instance").option("value",area_code);
													
													})
												}
											})
									})
								})
				

			}else{
				page.content.find(".data-grid").dxForm({
				dataSource:new DevExpress.data.CustomStore({
            	store:$.crudStore(API('restful?_model=sys-dealer'))
        			  }),
				showColonAfterLabel: true,
				colCount:1,
				items:items
					})
			}

			

			return 
		}

		

		let items = [{
				label:{text:'进口商名称'},
				dataField:'name'
			},{
				label:{text:'地址'},
				itemType:'group',
				colCount:3,
				items:[{
					label:{text:'省级'},
					template:function(data){
					return $("<div class='select_country'>").dxSelectBox({
								placeholder:'请选择省级',
								dataSource:$.crudStore(API("areas")),
								displayExpr:"name",
								valueExpr:'value',
								searchEnabled:true,
								onSelectionChanged:function(e){
									
									if(!e.selectedItem){return }
							page.content.find(".select_city").dxSelectBox("instance").option('dataSource',e.selectedItem.child);
							page.content.find(".select_region").dxSelectBox("instance").option("dataSource",[])
								}
							})
					}
				},{
					label:{text:'市级'},
					template:function(data){
					return	$("<div class='select_city'>").dxSelectBox({placeholder:'请选择市级',displayExpr:"name",
								valueExpr:'value',
								searchEnabled:true,
								noDataText:'请先选择前一级',
								onSelectionChanged:function(e){
									if(!e.selectedItem){return }
									page.content.find(".select_region").dxSelectBox("instance").option("dataSource",e.selectedItem.child)
								}
							})
					}
				},{
					label:{text:'地区'},
					template:function(data){
					return	$("<div class='select_region'>").dxSelectBox({placeholder:'请选择区域',displayExpr:"name",
								valueExpr:'value',
								searchEnabled:true,
								noDataText:'请先选择前一级',
								onValueChanged:function(e){
									page.content.find(".data-grid").dxForm("instance").option('formData.area_code',e.value);
								}
							})
					}
				}]
			},{
				label:{text:'具体门牌号'},
				dataField:'detail'
			},{
				label:{text:'联系人'},
				dataField:'linkman'
			},{
				label:{text:"电话"},
				dataField:'tel'
			},{
				label:{text:"邮箱"},
				dataField:'email'
			},{
				editorType:'dxButton',
				editorOptions:{
					text:function(){
						if(importer){
							return '修改'
						}else{
							return '创建'
						}},
					type:'success',
					useSubmitBehavior:false,
					onClick:function(e){

						let data=page.content.find(".data-grid").dxForm("instance").option('formData');
						let URL = 'restful?_model=sys-importer';
						let method = 'post';
						let text = '创建';
						if(importer){ 
							URL = `restful/${importer}?_model=sys-importer`;
							method = 'PUT';
							text = '修改'
						}

						$.ajax({url:API(URL),method:method,data:data}).always((res)=>{
							if(res.status == 'success'){ 
							DevExpress.ui.notify({message:text+"成功"},"success",1500) ;

			
							setTimeout(function(){window.history.go(-1);},1500)

						}else{
								DevExpress.ui.notify({message:function(){
									let text = '错误：'+res.responseJSON.message;
									return text
								}},"warning",1500)
							}
						}).fail(res=>{
							DevExpress.ui.notify({message:"请检查"},"warning",2000) 
						})
					}
				}
			}]

			


		if(importer){
			page.crudLayout({title:'编辑进口商'});

			page.content.html(`<div class="panel panel-default">
			    <div class="panel-heading font-bold">
			      进口商管理
			    </div>
			    <div class="panel-body">
			    	<div class="data-grid"></div>
			    </div>
		  	</div>`);

		page.content.find(".data-grid").css({"padding":"20px"});

			
			$.get(API(`restful/${importer}?_model=sys-importer`)).then(res => {
			
			page.content.find(".data-grid").dxForm({
			formData:res.data,
			showColonAfterLabel: true,
			colCount:1,
			items:items
		})
			let area_code=res.data.area_code;

				let country = area_code.slice(0,2)+'0000',city=area_code.slice(0,4)+'00' ;
								$.get(API("areas")).then(resp =>{
									let data =  resp;
									page.content.find(".select_country").dxSelectBox("instance").option("dataSource",resp);
									page.content.find(".select_country").dxSelectBox("instance").option("value",country);
									data.forEach( item =>{
										if(item.value == country){
											page.content.find(".select_city").dxSelectBox("instance").option("dataSource",item.child);
											page.content.find(".select_city").dxSelectBox("instance").option("value",city);
											return item.child.forEach(it=>{
												if(it .value == city)
												page.content.find(".select_region").dxSelectBox("instance").option("dataSource",it.child);
												page.content.find(".select_region").dxSelectBox("instance").option("value",area_code);
													
													})
												}
											})
									})

			})
			
		}else{
			page.crudLayout({title:'新建进口商'});

			page.content.html(`<div class="panel panel-default">
			    <div class="panel-heading font-bold">
			      进口商管理
			    </div>
			    <div class="panel-body">
			    	<div class="data-grid"></div>
			    </div>
		  	</div>`);

		page.content.find(".data-grid").css({"padding":"20px"});

			page.content.find(".data-grid").dxForm({
			dataSource:new DevExpress.data.CustomStore({
            store: $.crudStore(API('restful?_model=sys-importer'))
          }),
			showColonAfterLabel: true,
			colCount:1,
			items:items
		})
		}
		
		

		
	}
})